A recursive function is a function that calls itself to solve a problem. It is a porful programming technique used to break a complex problem into smaller sub-problems. Each recursive call reduces the original problem towards a base case where no further recursion is needed.
Recursive functions are particularly useful for problems that exhibit self-replicating structures or have sub-problems that resemble the original problem. To avoid infinite recursion, every recursive function must have a base case that stops the recursion.
In this example, 'll implement a recursive function to calculate the factorial of a non-negative integer.
#include <stdio.h>
// Recursive function to calculate factorial
unsigned long long int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: factorial(n) = n * factorial(n-1)
else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
unsigned long long int result = factorial(num);
printf("Factorial of %d is: %llu\n", num, result);
return 0;
}
Factorial of 5 is: 120
What is recursion in C?
What is a base case in recursion?
What is a recursive function's calling itself?
What is a recursive function's intermediate result?
What is a recursive function's control stack?